/**
 * 默认：
 */

package com.sky;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.BaseException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SearchHttpAK {
    @Autowired
    public static String URL = "https://api.map.baidu.com/geocoding/v3?";
    public static String AK = "IOYRNFmRwRz35yeFMWcymkstDkxTuSVy";
    public static String URL2 = "https://api.map.baidu.com/direction/v2/driving?";

    public static void main(String[] args) throws Exception {

        SearchHttpAK snCal = new SearchHttpAK();

        Map params = new LinkedHashMap<String, String>();
        params.put("address", "深圳市黑马程序员");
        params.put("output", "json");
        params.put("ak", AK);
//        params.put("callback", "showLocation");
        String origin = snCal.requestBaiduGetlongitudeAndLatitude(URL, params);
        Map params1 = new LinkedHashMap<String, String>();
        params1.put("address", "深圳市宝安区珊姐便利店");
        params1.put("output", "json");
        params1.put("ak", AK);
        String destination = snCal.requestBaiduGetlongitudeAndLatitude(URL, params1);
        Map params3 = new LinkedHashMap<String, String>();
        params3.put("origin", origin);
        params3.put("destination", destination);
        params3.put("ak", AK);
        String distence = snCal.requestGetdistence(URL2, params3);
        System.out.println("distence = " + distence);
    }

    private String requestGetdistence(String strUrl, Map<String, String> param)  throws Exception{
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            throw new BaseException("参数错误");
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer.toString());
        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(buffer)).getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        Object o = jsonObject.get("distance");
        return o.toString();
    }

    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    public String requestBaiduGetlongitudeAndLatitude(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            throw new BaseException("地址不正确");
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println(buffer);
        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(buffer)).getJSONObject("result").getJSONObject("location");
        String  lng = jsonObject.get("lng").toString();
        String lat = jsonObject.get("lat").toString();
        return lat+"," + lng;
    }
}